package booyah.web;

import booyah.application.User;
import booyah.service.EventService;
import booyah.service.UserService;
import booyah.validation.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    private final UserService userService;
    private final EventService eventService;


    @Autowired
    public UserController(UserService userService, EventService eventService) {
        this.userService = userService;
        this.eventService = eventService;
    }

    @ModelAttribute
    public User newRequest(@RequestParam(required = false) Long id) {
        return (id != null) ? userService.findUserById(id) : new User();
    }

    @RequestMapping(method = RequestMethod.GET)
    public void show(Model model, HttpSession session) {
        model.addAttribute("user", session.getAttribute("user"));
    }


    @RequestMapping(method = RequestMethod.GET)
    public void form() {
        System.out.println("form GET");
    }


    @RequestMapping(method = RequestMethod.POST)
    public String form(@ModelAttribute User user, BindingResult result, SessionStatus status, HttpSession session) {
        UserValidator.validate(user, result);
        if (result.hasErrors()) {
            return null; // Default view
        } else {
            userService.updateUser(user);
            status.setComplete();
            if (user.isNew()) {
                return "redirect:/signout";
            }
            session.setAttribute("user", user);
            return "redirect:/controller/user/show?id=" + ((User) session.getAttribute("user")).getId();
        }
    }

}
